<template>
    <el-main v-loading="loading">
        <div class="margin_bottom_30">
            <el-button type="primary" size="small" @click="handleActionPage">新增权益</el-button>
        </div>
        <el-table
            :data="dataList"
            border
            :row-key="row => row.medalEquityUid"
            height="640"
            :header-cell-style="{background:'#afafaf',color:'#606266'}"
            ref="multipleTable"
            @selection-change="handleSelectionChange"
        >
            <el-table-column align="center" type="selection" reserve-selection width="40"></el-table-column>
            <el-table-column align="center" width="150" label="权益标题">
                <template slot-scope="scope">
                    <el-tooltip :content="scope.row.medalEquityTitle">
                        <p>{{scope.row.medalEquityTitle | controlLength}}</p>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column align="center" width="100" label="权益图片">
                <template slot-scope="scope">
                   <img v-image-preview v-if="scope.row.medalEquityImageUrl" width="60" :src="scope.row.medalEquityImageUrl" />
                </template>
            </el-table-column>
            <el-table-column align="center" width="150" label="权益描述">
                <template slot-scope="scope">
                    <el-tooltip :content="scope.row.medalEquityName">
                        <p>{{scope.row.medalEquityName | controlLength}}</p>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" align="center" width="160" label="创建时间"></el-table-column>
            <el-table-column prop="medalEquityType" align="center" width="100" label="权益类型">
                <template slot-scope="scope">
                    {{getMedalEquityType(scope.row.medalEquityType)}}
			    </template>
            </el-table-column>
            
            <el-table-column width="200" align="center" label="权益信息">
                <template slot-scope="scope">
                    <el-tooltip :content="item.medalEquityName" v-for="(item, index) of scope.row.medalRightItems" :key="index">
                        <div class="rightItems">
                            <img class="rightItems_icon" v-image-preview v-if="item.medalEquityImage" :src="item.medalEquityImage" />
                            <p class="rightItems_name">{{item.medalEquityName | controlLength}}</p>
                        </div>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column prop="saleCount" align="center" width="200" label="关联勋章">
                <template slot-scope="scope">
                    <el-tooltip :content="item.medalName" v-for="(item, index) of scope.row.bindMedals" :key="index">
                        <div class="iten_list">
                            <p class="iten_list_span">{{item.medalName | controlLength}}</p>
                            <P>
                                <img class="iten_list_icon" v-image-preview v-if="item.medalImageUrlOn" :src="item.medalImageUrlOn" />
                                <img class="iten_list_icon" v-image-preview v-if="item.medalImageUrlOff" :src="item.medalImageUrlOff" />
                            </P>
                        </div>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column prop="memberGetRightCount" align="center" width="200" label="被获取次数"></el-table-column>
            <el-table-column align="center"  label="操作" width="200">
                <template slot-scope="scope">
                    <el-button type="text" @click="handleEdit(scope.row)" size="small">编辑</el-button>
                    <el-button type="text" @click="handleDel(scope.row)" size="small">删除</el-button>
                    <!-- <template v-if="scope.row.status === 1">
                        <el-button type="text" @click="handleUpdate(scope.row)" size="small">下架</el-button>
                    </template>
                    <template v-else>
                        <el-button type="text" @click="handleUpdate(scope.row)" size="small">上架</el-button>
                    </template> -->
                </template>
            </el-table-column>
        </el-table>

        <el-row class="footer">
            <el-col :span="12">
				<el-checkbox
                    v-model="checkAll"
                    :disabled="!dataList.length"
                    @change="handleCheckAllChange">全选
                </el-checkbox>
			</el-col>
			<el-col :span="12">
				<el-pagination
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    :page-size="10"
                    background
                    :disabled="!dataList.length"
                    :total="count"
                    class="text_align_right"
                    layout="total, prev, pager, next, jumper">
                </el-pagination>
			</el-col>
		</el-row>
      
		<el-dialog
            :title="!goodsInfo.productUid ? '新增权益' : '编辑权益'"
            @close="handleCloseAction"
            :visible.sync="showActionPage"
            destroy-on-close
            :modal-append-to-body="false"
            :close-on-click-modal="false"
            width="50%">
			<medal-rights-action
                :infoData="goodsInfo"
                ref="medalRightRef"
                :medalEquityTypeList="medalEquityTypeList"
                :redPacketList="redPacketList"
                :relationGoods="relationGoods"
                @func="closeTemplatePage"
                :goodsDataList="goodsDataList"></medal-rights-action>
		</el-dialog>

        <related-products :show="showRelatedProducts" :relatedProductsData="relatedProductsData" />
    </el-main>
</template>
<script>
    import medalRightsAction from './rights/index.vue';
    import relatedProducts from '@/components/RelatedProducts';
    import {
        rightsList,
        deleteRights,
        redPacket,
        getGoodslist,
        updateGoodsState
	} from "@/api/table";
    import utils from '@/utils/utils';

    export default {
        name: "RIGHTS_LIST",
        filters: {
            controlLength: curStr => utils.controlLength(curStr, 18),
        },
        data() {
            return {
                showRelatedProducts: false,
                count: 0,
                checkAll: false, // 全选
                goodsDataList: [], // 商品列表
                relationGoods: [],
                dataList: [],
                loading: true,
                page: 1,
                showActionPage: false,
                goodsInfo: {},
                redPacketList: [],
                relatedProductsData: [],
                medalEquityTypeList: [
					{
						labelId: 0,
						labelText: '红包'
					}, {
						labelId: 1,
						labelText: '商品'
					}
				], 
            }
        },
        components: {
            medalRightsAction,
            relatedProducts
        },
        mounted() {
            this.getData();
            this.getPacketList();
            this.getGoodslistData();
            // 监听消息
            this.$event.on('ShowRelatedProducts', data => {
                this.relatedProductsData = data;
                this.showRelatedProducts = true
            });
            this.$event.on('RelatedProducts', data => {
                this.relationGoods = data;
                this.showRelatedProducts = false
            });
            this.$event.on('CloseRelatedProducts', () => {
                this.showRelatedProducts = false;
            });
        },
        beforeDestroy() {
            this.$event.off('ShowRelatedProducts')
            this.$event.off('RelatedProducts')
            this.$event.off('CloseRelatedProducts')
        },
        methods: {
            // 获取权益类型
            getMedalEquityType(id) {
                const info = this.medalEquityTypeList.find(item => item.labelId === id) || {};
                return info.labelText || ''
            },
            // 搜索
            search() {
                this.getData();
            },
            // 获取商品列表
            getGoodslistData() {
                getGoodslist({
                    status: '1',
                    page: 0,
                    size: 50
                }).then(res => {
                    if (res.data.isSuccessful === "Y") {
                        const { productList } = res.data.data;
                        this.goodsDataList  = productList;
                    }
                });
            },
            //加载第几页
            handleCurrentChange(val) {
                this.page = val;
                //修改页数，重新加载
                this.getData();
            },
            // 全选
            handleCheckAllChange(val) {
                if (this.checkAll) {
                    this.$refs.multipleTable.toggleAllSelection();
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },
            resetQuery() {
                this.page = 1;
                this.getData();
            },
			handleClose() {
                this.handleCloseAction()
            },

            handleCloseAction() {
                this.goodsInfo = {};
                this.relationGoods = [];
            },

            handleActionPage() {
                this.showActionPage = true
            },
            closeTemplatePage(data) {
                this.handleCloseAction()
                this.showActionPage = data.action;
                data.refresh && this.getData();
            },
            // 监听选择的内容
            handleSelectionChange(val) {
                // console.log(val)
                this.checkAll = this.dataList.length === val.length
            },
            // 获取红包列表
			getPacketList() {
				redPacket({
                    redPacketType: 0,
                    page: 0,
                    size: 50
                }).then(res => {
                    if (res.data.isSuccessful === "Y") {
                        this.redPacketList  = res.data.data.redPacketList;
                    }
                })
                .catch(() => {});
			},
            // 获取数据
            getData() {
                rightsList({
                    page: this.page - 1
                }).then(res => {
                    if (res.data.isSuccessful === "Y") {
                        const {
                            count,
                            rights
                        } = res.data.data;
                        this.count = count;
                        this.dataList  = rights;
                    }
                })
                .catch(err => {})
                .finally(() => {
                    if (this.loading) {
                        this.loading = false
                    }
                });
            },
            // 编辑
            handleEdit(info) {
                this.goodsInfo = info;
                this.handleActionPage();
                // 同步数据
				this.$nextTick(() => {
					this.$refs.medalRightRef.updateData()
				})
            },
            // 更改状态
            handleUpdate(info) {
                this.$confirm( `是否${info.status !== 1 ? '上架' : '下架'}该权益?`, "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                     let status = info.status !== 1 ? 1 : 2;
					updateGoodsState({
                        productUid: info.productUid,
                        status
                    }).then(res => {
                        if(res.data.isSuccessful !== "Y"){
                            this.$message.error(res.data.message);
                            return
                        }

                        this.$message.success(res.data.message);
                        setTimeout(() => {
                            this.getData();
                        }, 500)
                    }).catch(err => {});
				}).catch();
            },
            // 删除
            handleDel(info) {
                this.$confirm("是否删除该权益?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
					deleteRights({
                        medalEquityUid: info.medalEquityUid,
                    }).then(result => {
                        if(result.data.isSuccessful !== "Y"){
                            this.$message.error(result.data.message);
                            return
                        }

                        this.$message.success(result.data.message);
                        this.dataList = this.dataList.filter(item => item.medalEquityUid !== info.medalEquityUid);
                        setTimeout(() => {
                            this.getData();
                        }, 500)
                    }).catch(err => {});
				}).catch(() => {
					this.$message({
						type: "info",
						message: "已取消"
					});
				});
            },
        }
    }
</script>
<style lang="scss" scoped>

    .iten_list{
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        margin-bottom: 10px;
        &_icon {
            margin: 0 5px;
            height: 60px;
            width: 60px;
            object-fit: contain;
        }
        &_span {
            margin-bottom: 10px;
        }
    }
    .rightItems {
        display: flex;
        align-content: center;
        margin-bottom: 10px;
        &_name {
            margin-left: 10px;
            text-align: left;
            font-size: 12px;
            line-height: 1.8;
        }
        &_icon {
            height: 40px;
            width: 40px;
            object-fit: cover;
            border-radius: 5px
        }
    }
</style>
